//
//  FPMapViewController.m
//  FilmParadise
//
//  Created by lanou3g on 15/7/23.
//  Copyright (c) 2015年 DLYgroup. All rights reserved.
//

#import "FPMapViewController.h"
#import "FPLocation.h"

@interface FPMapViewController ()<BMKMapViewDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKPoiSearchDelegate,UITextFieldDelegate>
{
    BMKMapView *_mapView;
    UIButton *_startBtn;
    UIButton *_stopBtn;
    UIButton *_followingBtn;
    UIButton *_followHeadBtn;
    
    UITextField *_cityText;
    UITextField *_keyText;
    UIButton *_nextPageButton;
    UIButton *_searchButton;
    
   
    int curPage;
    
    float _currentLatirude;
    float _currentLongitude;
}

@property (nonatomic, strong) NSMutableArray *cinemaNameArray;
@property (nonatomic, strong) NSMutableArray *cinemaAddressArray;
@property (nonatomic, strong) NSMutableArray *currentDistanceArray;

@end

@implementation FPMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 90, kScreenWidth, kScreenHeight)];
    [self.view addSubview:_mapView];
    
    _cityText = [[UITextField alloc] initWithFrame:CGRectMake(0, 60, 70, 30)];
    _cityText.text = @"北京";
    _cityText.borderStyle = UITextBorderStyleBezel;
    _cityText.delegate = self;
    [self.view addSubview:_cityText];
    
    _keyText = [[UITextField alloc] initWithFrame:CGRectMake(70, 60, 100, 30)];
    _keyText.text = @"电影院";
    _keyText.borderStyle = UITextBorderStyleBezel;
    _keyText.delegate = self;
    [self.view addSubview:_keyText];
    
    _searchButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _searchButton.frame = CGRectMake(170, 60, 50, 30);
    [_searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    [_searchButton addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_searchButton];
    
    _nextPageButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _nextPageButton.frame = CGRectMake(220, 60, 100, 30);
    [_nextPageButton setTitle:@"下一组数据" forState:UIControlStateNormal];
    [_nextPageButton addTarget:self action:@selector(nextSearch) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextPageButton];
    
    // 设置地图级别
    [_mapView setZoomEnabled:13];
    _nextPageButton.enabled = false;
    _mapView.isSelectedAnnotationViewFront = YES;
    /*----------------------------------------------------------------------*/
    _startBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _startBtn.frame = CGRectMake(0, 30, 90, 30);
    [_startBtn setTitle:@"开始定位" forState:UIControlStateNormal];
    [_startBtn addTarget:self action:@selector(startLocation) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_startBtn];
    
    _stopBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _stopBtn.frame = CGRectMake(90, 30, 90, 30);
    [_stopBtn setTitle:@"使用跟随" forState:UIControlStateNormal];
    [_stopBtn addTarget:self action:@selector(startFollowHeading) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_stopBtn];
    
    _followHeadBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _followHeadBtn.frame = CGRectMake(180, 30, 90, 30);
    [_followHeadBtn setTitle:@"使用罗盘" forState:UIControlStateNormal];
    [_followHeadBtn addTarget:self action:@selector(startFollowing) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_followHeadBtn];
    
    _followingBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _followingBtn.frame = CGRectMake(270, 30, 90, 30);
    [_followingBtn setTitle:@"停止定位" forState:UIControlStateNormal];
    [_followingBtn addTarget:self action:@selector(stopLocation) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_followingBtn];
    
    
    
    // 适配
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 7.0) {
        self.navigationController.navigationBar.translucent = NO;
    }
    _locService = [[BMKLocationService alloc] init];
    
}
- (BMKPoiSearch *)poisearch
{
    if (!_poisearch)
    {
        _poisearch = [[BMKPoiSearch alloc]init];
        _poisearch.delegate = self;
    }
    return _poisearch;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _poisearch = [[BMKPoiSearch alloc] init];
    _mapView.delegate = self;// 此处不用的时候要置为nil,否则影响内存释放
    _locService.delegate = self;
//    _poisearch.delegate = self;
}

//- (void)viewWillDisappear:(BOOL)animated
//{
//    [_mapView viewWillDisappear];
//    _mapView.delegate = nil;
//    _locService.delegate = nil;
//    _poisearch.delegate = nil;
//}

- (void)startLocation
{
    NSLog(@"进入普通定位态");
    [_locService startUserLocationService];
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeNone;
    _mapView.showsUserLocation = YES;
}

- (void)startFollowHeading
{
    NSLog(@"进入罗盘");
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeFollowWithHeading;
    _mapView.showsUserLocation = YES;
}

- (void)startFollowing
{
    NSLog(@"进入跟随状态");
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    _mapView.showsUserLocation = YES;
    
}

- (void)stopLocation
{
    [_locService stopUserLocationService];
    _mapView.showsUserLocation = NO;
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 地图启动
- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}

// 用户方向更新后
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    NSLog(@"heading is %@",userLocation.heading);
}

// 用户位置更新后,会调用此函数
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    _currentLatirude = userLocation.location.coordinate.latitude;
    _currentLongitude = userLocation.location.coordinate.longitude;
    NSLog(@"%f------%f",_currentLatirude,_currentLongitude);
    NSLog(@"用户更新了位置");
}
// 地图view停止定位后,会调用此函数
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}

// 定位失败后,会调用此函数
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}
/*===========================================================================*/
- (void)search
{
//    [self stopLocation];
    curPage = 0;
    BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc] init];
//    citySearchOption.pageIndex = curPage;
//    citySearchOption.pageIndex = 10;
//    citySearchOption.city      = [FPLocation shareInstance].cityLocal;
    citySearchOption.city = @"上海";
    NSLog(@"%@",citySearchOption.city);

//    FPNearbyTableViewController * FPNearVC = [[FPNearbyTableViewController alloc]init];
//    [self.navigationController pushViewController:FPNearVC animated:YES];
    
    

//    [_cinemaNameArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        NSString *str = _cinemaNameArray[idx];
//        citySearchOption.keyword = str;
//        NSLog(@"///////////%@",str);
//        NSLog(@"----++++%@",_keyText.text);
//    }];                                                           
    citySearchOption.keyword = _keyText.text;
    

    
    BOOL flag = [self.poisearch poiSearchInCity:citySearchOption];
    if (flag) {
        NSLog(@"城市内检索发送成功");
    }else
    {
        NSLog(@"城市内检索发送失败");
    }
}

- (void)nextSearch
{
    curPage ++;
    BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc] init];
    citySearchOption.pageIndex = 10;
    citySearchOption.city      = [NSString stringWithFormat:@"%@",[FPLocation shareInstance].locationID];
//    [_cinemaNameArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        NSString *str = _cinemaNameArray[idx];
//        citySearchOption.keyword = _keyText.text;
//        NSLog(@"\\\\\\\\\\\%@",str);
//    }];
    citySearchOption.keyword = _keyText.text;
    BOOL flag = [_poisearch poiSearchInCity:citySearchOption];
    if (flag) {
        NSLog(@"城市内检索发送成功");
    }else
    {
        NSLog(@"城市内检索发送失败");
    }

}
#pragma mark - 
#pragma mark BMKMapViewDelegate
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation
{
    // 生成重用标示identifier
    NSString *AnnotationViewID = @"xidanMark";
    
    // 检查是否有重用的缓存
    BMKAnnotationView* annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    
    // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        // 设置重天上掉下的效果(annotation)
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
    
    // 设置位置
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
    annotationView.canShowCallout = YES;
    // 设置是否可以拖拽
    annotationView.draggable = NO;
    
    return annotationView;

}

- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    [mapView bringSubviewToFront:view];
    [mapView setNeedsDisplay];
}
- (void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    NSLog(@"didAddAnnotationViews");
}

#pragma mark -
#pragma mark implement BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{
    // 清楚屏幕中所有的annotation
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    
    if (error == BMK_SEARCH_NO_ERROR) {
        NSMutableArray *annotations = [NSMutableArray array];
        self.currentDistanceArray   = [NSMutableArray array];
        self.cinemaNameArray        = [NSMutableArray array];
        self.cinemaAddressArray     = [NSMutableArray array];
        for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
            item.coordinate = poi.pt;
            item.title = poi.name;
            BMKMapPoint point1 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake(_currentLatirude, _currentLongitude));
            BMKMapPoint point2 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake(poi.pt.latitude, poi.pt.longitude));
            CLLocationDistance distance = BMKMetersBetweenMapPoints(point1, point2);
            NSLog(@"-=-=-=-=-==%f",distance);
            [self.currentDistanceArray addObject:[NSString stringWithFormat:@"%f",distance]];
            [self.cinemaNameArray addObject:poi.name];
            [self.cinemaAddressArray addObject:poi.address];
            NSLog(@"--------%@",poi.name);
            [annotations addObject:item];
        }
        
           if (self.block != nil)
           {


               self.block(@"北京");
            }

        
        
        [_mapView addAnnotations:annotations];
        [_mapView showAnnotations:annotations animated:YES];
        
    } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
        NSLog(@"起始点有歧义");
    } else {
        // 各种情况的判断。。。
    }
}

//- (NSMutableArray *)currentDistanceArray
//{
//    if (!_currentDistanceArray) {
//        _currentDistanceArray = [NSMutableArray array];
//    }
//    return _currentDistanceArray;
//}
//
//- (NSMutableArray *)cinemaAddressArray
//{
//    if (!_cinemaAddressArray) {
//        _cinemaAddressArray = [NSMutableArray array];
//    }
//    return _cinemaAddressArray;
//}
//
//- (NSMutableArray *)cinemaNameArray
//{
//    if (!_cinemaNameArray) {
//        _cinemaNameArray = [NSMutableArray array];
//    }
//    return _cinemaNameArray;
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
